import apiAddr from './addr';
import $http from './config';
//判断是否是路径参数的url:stirng
function isPathParams(url) {
    return url.lastIndexOf('/') === url.length - 1;
}

// params {} 对象类型
function createFromData(params) {
    const result = new FormData();
    for (const key in params) {
        result.append(key, params[key]);
    }
    return result;
}


function generatorApiFunc(pathconf) {
    return (data = {}, opt) => {
        return new Promise((resolve, reject) => {
            let newUrl = pathconf.url;
            if (isPathParams(pathconf.url)) {
                newUrl += data;
                data = ''
                if (opt) {
                    // 处理 路径 参shu 传formdata的情况
                    data = opt;
                }
            }
            $http({
                url: newUrl,
                params: pathconf.method === 'GET' ? data : null,
                data: pathconf.isFormData ? createFromData(data) : data,
                method: pathconf.method,
            }).then((res) => {
                if (res.code === 200) {
                    resolve(res.data);
                } else {
                    reject(res);
                }
            }).catch((err) => {
                console.warn(`请求错误----url=${pathconf.url}`, pathconf.method, data);
                console.error(err);
                reject(err);
            }).finally(() => {

            });

        });

    };

}

const API = {}

for (const key in apiAddr) {
    API[key] = generatorApiFunc(apiAddr[key]);
}

export default API;
